# The pyPDF library was obtained from
# http://pybrary.net/pyPdf/
# and works a treat!
from pyPdf import PdfFileWriter, PdfFileReader
# Import 'copy' from the standard library.
# Needed for duplicating PDF page objects.
import copy

# This is hard coded for the moment; now that things work,
# I'll start thinking about interface.
inpdf  = PdfFileReader(file("paper.pdf", "rb"))
outpdf = PdfFileWriter()

# I have no idea if there's something built
# into Python to do this; I wrote my own 
# 'isEven' to tell me if a number is even or not.
def isEven(x):
	if ((x % 2) == 0):
		return True
	else:
		return False

# Performs the crop to the upper half of a page,
# and rotates it counter-clockwise 90 degrees.
def cropToUpperHalf(page):
	print "cropToUpperHalf"
	page.cropBox.setLowerLeft(
		(0, (page.mediaBox.getUpperLeft_y() / 2)))
	page.cropBox.setUpperRight(
	(page.mediaBox.getLowerRight_x(), 
	 page.mediaBox.getUpperRight_y()))
	page.rotateCounterClockwise(90)
	return page

# Performs the crop to the lower half of a page,
# and rotates it counter-clockwise 90 degrees.
def cropToLowerHalf(page):
	print "cropToLowerHalf"
	page.cropBox.setLowerLeft((0, 0))
	page.cropBox.setUpperRight(
		(page.mediaBox.getLowerRight_x(),
		(page.mediaBox.getUpperRight_y() / 2)))
	page.rotateCounterClockwise(90)
	return page

# An even/odd flip-flop; unlike the Perl library,
# pages start with 0 in the Python library, not 1.
outputCounter = 0

for pg in range(inpdf.getNumPages()):
	# First, get a reference to the page object
	# at the current index.
	thepage = inpdf.getPage(pg)

	# For each page, produce a top half and a bottom half.
	for split in range(2):
		print "Fetching page %s, pass %s" % (pg, split)

		# Now, copy the page object. Otherwise,
		# we'll be performing multiple operations on
		# the same object reference. 
		# http://docs.python.org/lib/module-copy.html
		page = copy.copy(thepage)
		
		# Do the half-page crop. If it is an even 
		# page count, it must be the top half we want;
		# otherwise, we want the bottom half.
		if(isEven(outputCounter)):
			outpdf.addPage(cropToUpperHalf(page))
		else:
			outpdf.addPage(cropToLowerHalf(page))

		# Bump the output counter.
		outputCounter = outputCounter + 1

# Now, write the file
outputStream = file("split-paper.pdf", "wb")
outpdf.write(outputStream)
outputStream.close()


